import store from '@/store';
import { logout } from '@/store/actions';
import { message } from 'antd';
import axios from 'axios';
import customHistory from './history';

import { isAuth } from './token';

const baseURL = process.env.REACT_APP_URL;
const http = axios.create({
  // baseURL: 'http://geek.itheima.net/v1_0',
  baseURL,
});

// 请求拦截器
http.interceptors.request.use(config => {
  const { login: token } = store.getState();
  if (isAuth()) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  return config;
});

// 响应拦截器  处理token失效的方法
http.interceptors.response.use(undefined, error => {
  // 网络超时
  if (!error.response) {
    message.error('请求繁忙，请稍后再试', 1);
    return Promise.reject(error);
  }

  // 登陆超时
  if (error.response.status === 401) {
    message.error('登陆超时，请重新登陆', 1, () => {
      customHistory.push('/login', {
        from: customHistory.location.pathname,
      });

      // 触发退出action 清除登陆信息
      store.dispatch(logout());
    });
  }
  return Promise.reject(error);
});

export { http };
